package com.luoqiz.security.config.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Configuration
public class CommonWebMvcConfig extends WebMvcConfigurationSupport {

	@Value("${upload.file-path:/data1/upload/}")
	private String uploadFilePath;

	@Autowired
	private HttpMessageConverter<?> jsonHttpMessageConverter;

	@Override
	protected void addInterceptors(InterceptorRegistry registry) {
		// 注册自定义拦截器，添加拦截路径和排除拦截路径
		// registry.addInterceptor(new
		// InterceptorConfig()).addPathPatterns("/api/**")/*.excludePathPatterns("/api/**")*/;
		super.addInterceptors(registry);
	}

	@Override
	protected void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**").allowCredentials(true).allowedHeaders("*").allowedOrigins("*").allowedMethods("*");
		super.addCorsMappings(registry);
	}

	@Override
	protected void addResourceHandlers(ResourceHandlerRegistry registry) {
		super.addResourceHandlers(registry);
		// spring boot 默认的资源位置配置
		registry.addResourceHandler("/upload/**").addResourceLocations("file:///" + uploadFilePath);
		registry.addResourceHandler("/**").addResourceLocations("classpath:/static/", "classpath:/public/",
				"classpath:/resources/", "classpath:/META-INF/resources/");
		registry.addResourceHandler("/**/favicon.ico").addResourceLocations("classpath:/**/favicon.ico");
//		registry.addResourceHandler("/webjars/**").addResourceLocations("/webjars/").resourceChain(false)
//				.addResolver(new WebJarsResourceResolver()).addResolver(new PathResourceResolver());
	}

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		super.configureMessageConverters(converters);
		converters.add(jsonHttpMessageConverter);
		StringHttpMessageConverter converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
		converters.add(converter);
	}


	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/login").setViewName("login");
		registry.addViewController("/oauth/confirm_access").setViewName("authorize");
	}

}
